package com.example.tliasfight.filter;

import com.alibaba.fastjson.JSONObject;
import com.example.tliasfight.pojo.Result;
import com.example.tliasfight.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter
{
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
    {//获取请求的url
        HttpServletRequest req =(HttpServletRequest)servletRequest;
        HttpServletResponse resp=(HttpServletResponse)servletResponse;
        String url=req.getRequestURI().toString();

        //判断url是否含login
        if(url.contains("login"))
        {
            log.info("这是一次登录请求");
            filterChain.doFilter(servletRequest,servletResponse);//放行
            return;
        }
        else//不是登录请求，就看一下另外是否能被成功解析
        {
            //看看请求的token是否携带jwt令牌
            String value=req.getHeader("token");
            if(value == null|| value.equals(""))
            {
                log.info("请求头里面没有jwt令牌，说明是直接复制网页地址的未登录");
                Result error=Result.error("NOT_LOGIN");
                String jsonString = JSONObject.toJSONString(error);
                resp.getWriter().write(jsonString);
                return;
            }
            log.info("请求头里面有jwt令牌，开始解析");
            try {
                JwtUtils.parseJwt(req.getHeader("token"));
                filterChain.doFilter(servletRequest,servletResponse);
            } catch (Exception e) {
                e.printStackTrace();
                log.info("解析令牌失败，可能篡改了也可能过期了");
                Result error=Result.error("NOT_LOGIN");
                String jsonString = JSONObject.toJSONString(error);
                resp.getWriter().write(jsonString);
                return;


            }
        }






    }
}
